<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>文件上传</title>
</head>
<body>
    <div>
        <button id="upload">上传文件</button>
        <input type="file" name="headImage" style="display: none;" multiple="multiple">
    </div>
</body>

<script src="main/js/jquery.min.js?v=2.1.4"></script>
<script src="main/js/plugins/validate/jquery.validate.min.js"></script>
<script src="main/common/js/aes.js" type="text/javascript"></script>
<script src="main/common/js/CommonUtils.js"></script>
<script>
    $(function () {
        $("#upload").click(function(){
            $("input[name='headImage']").click();
        })
        $(document).on('change', "input[name='headImage']", function(){
            var ts=this;
            console.log("length："+ this.files.length)
            if(this.files.length > 1){
                //消息提示款
                console.log("上传图片总数不能超过1个！");
                $("input[name='headImage']").val("");
                return;
            }
            for(var i = 0; i < this.files.length; i++){
                var fileSize = this.files[i].size;
                if(fileSize>5*1024*1024){
                    //消息提示款
                    console.log("上传图片已超过5M！");
                    $("input[name='headImage']").val("");
                    return;
                }
                var fileName=this.files[i].name;
                var suffixIndex=fileName.lastIndexOf(".");
                var suffix=fileName.substring(suffixIndex+1).toUpperCase();
                if(suffix=="JPG"||suffix=="PNG"){
                    uploadType=2;
                }else{
                    //消息提示款
                    console.log("请上传正确格式!(图片支持JPG、PNG格式。)");
                    $("input[name='headImage']").val("");
                    return;
                }
            }
            //创建FormData对象
            var data = new FormData();
            //为FormData对象添加数据
            $.each($(this)[0].files, function(i, file) {
                data.append('upload_file', file);
            });
            var FileController;
            if(uploadType==2){//图片
                FileController = '/init/user/upload';
            }
            $.ajax({url:FileController,
                data:data,
                type:'post',
                dataType:'json',
                processData: false,
                contentType: false,
                success:function(rs) {
                    if(rs.result){
                        //消息提示款
                        alert("上传成功")
                    } else {
                        //消息提示款
                        alert("上传失败")
                    }
                }
            });
        });

    })
</script>

</html>